import { call, put, takeLatest } from 'redux-saga/effects';
import { ADD_BOOK,addBook,updateBook } from '../actions/books.action';
import Message from '../components/SimpleLayer/Message';
import API from '../services';

function mess(type,content,time=1200){
  Message[type]({
    top:'6px',
    width:'300',
    content,
    delayAutoClose:time,
    yes:false
  });
}
function showErr(content){
	mess('error',content);
}
function* AddBook(action) {
   try {
      	const res = yield call(API.AddBook, action.data);
  		if (res.success) {
  			if (!action.data.id) {
  				// 新增
  				yield put(addBook(res.result));
  			}else{
  				yield put(updateBook(res.result));
  			}
        document.body.removeChild(document.querySelector('.yss-layer-box'));
        mess('success',(action.data.id?'修改':'新增')+'成功！');
		}else{
			showErr(res.result);
		}
   } catch (e) {
      	showErr(e.message);
   }
}

function* AddBookSaga() {
  yield takeLatest(ADD_BOOK, AddBook);
}

export default AddBookSaga;